/**
 * Created with IntelliJ IDEA.
 * @author: cxs
 * @date: 2023/6/26
 * @time: 20:23
 * @className：LoginController
 * @description：
 */
package com.bailan.sys.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.bailan.common.util.SysConstant;
import com.bailan.common.util.WebUtils;
import com.bailan.sys.domain.User;
import com.bailan.sys.vo.UserVo;
import com.bailan.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("login")
public class LoginController {
    @Autowired
    IUserService userService;
    /**
     * 跳转至登录界面
     *  @return
     */
    @RequestMapping("toLogin")
    public  String toLogin(){
        return "system/main/login";
    }
    /**
     * 获取验证码
     */
    @RequestMapping("getCode")
    public  void getCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        /*定义图形和干扰线*/
        LineCaptcha lineCaptcha= CaptchaUtil.createLineCaptcha(116,36,4,5);
        //将生成的验证码放入session中
        session.setAttribute("code",lineCaptcha.getCode());
        //获取输出流
        ServletOutputStream outputStream= response.getOutputStream();
        ImageIO.write(lineCaptcha.getImage(),"JPEG",outputStream);
    }
    /**
     * 登录模块实现
     */
    @RequestMapping("login")
    public  String login(UserVo userVo, Model model){
        //取出存入session中的验证码
       String code= WebUtils.getHttpSession().getAttribute("code").toString();
       if (userVo.getCode().equals(code)){
           User user=userService.login(userVo);
           if (null!=user){
               //如果用户存在，则跳转到index页面，并将用户信息转到index页面
               WebUtils.getHttpSession().setAttribute("user",user);
               return "system/main/index";
           }else{
               model.addAttribute("error", SysConstant.USER_LOGIN_ERROR_MSG);
               return "system/main/login";
           }
       }else {
           model.addAttribute("error",SysConstant.USER_LOGIN_CODE_ERROR_MSG);
           return "system/main/login";
       }
    }
}
